package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/16 15:15
 */
public class Flink10_Process_KeyBy {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<WaterSensor> s1 = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 2L, 40),
            new WaterSensor("sensor_3", 2L, 40),
            new WaterSensor("sensor_1", 5L, 50)
        );
    
        s1
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, Integer>() {
                Map<String, Integer> idToSum = new HashMap<String, Integer>();
            
                @Override
                public void processElement(WaterSensor input,
                                           Context ctx,
                                           Collector<Integer> out) throws Exception {
                    Integer sum = idToSum.getOrDefault(ctx.getCurrentKey(), 0);
                    
                    sum += input.getVc();
                    out.collect(sum);
                    idToSum.put(ctx.getCurrentKey(), sum);
                
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
 
 
 
 
 */